#include "UploadHelper.h"

#include <QDebug>

#include "UploadWorker.h"

namespace Upload {

UploadHelper::UploadHelper(const QString &id, const Config &config, QObject *parent)
    : QObject(parent), m_id(id), m_running(false)
{
    // 创建工作线程
    m_thread = new QThread(this);

    // 创建工作对象
    m_worker = new UploadWorker(id, config);

    // 将工作对象移动到工作线程
    m_worker->moveToThread(m_thread);

    // 连接信号槽
    connect(m_thread, &QThread::started, m_worker, &UploadWorker::start);
    connect(m_thread, &QThread::finished, m_worker, &UploadWorker::stop);
    connect(m_thread, &QThread::finished, m_worker, &QObject::deleteLater);

    // 转发worker的信号
    connect(m_worker, &UploadWorker::uploadSuccess, this, &UploadHelper::uploadSuccess);
    connect(m_worker, &UploadWorker::uploadError, this, &UploadHelper::uploadError);
    connect(m_worker, &UploadWorker::statusChanged, this, &UploadHelper::statusChanged);
    connect(m_worker, &UploadWorker::statusChanged, this,
            [this](const QString &, bool running) { m_running = running; });

    // 连接停止信号
    connect(this, &UploadHelper::stopRequested, m_worker, &UploadWorker::stop);
}

UploadHelper::~UploadHelper()
{
    stop();

    if (m_thread->isRunning()) {
        m_thread->quit();
        if (!m_thread->wait(3000)) {
            m_thread->terminate();
            m_thread->wait(1000);
        }
    }
}

void UploadHelper::start()
{
    if (m_running || m_thread->isRunning()) {
        return;
    }

    // 启动线程，线程启动后会自动调用worker的start方法
    m_thread->start();

    qDebug() << "UploadHelper thread started for" << m_id;
}

void UploadHelper::stop()
{
    if (!m_running && !m_thread->isRunning()) {
        return;
    }

    // 通过信号停止worker
    emit stopRequested();

    // 退出线程
    m_thread->quit();
    if (!m_thread->wait(3000)) {
        qWarning() << "Thread for" << m_id << "did not quit gracefully, terminating";
        m_thread->terminate();
        m_thread->wait(1000);
    }

    m_running = false;
    qDebug() << "UploadHelper thread stopped for" << m_id;
}

bool UploadHelper::isRunning() const { return m_running; }

}  // namespace Upload